<template>
  <el-dialog
    title="选择优惠券"
    v-model="visible"
    width="1100px"
    @close="onClose"
    :close-on-click-modal="false"
    :lock-scroll="false"
  >
    <div class="main">
      <el-form :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item label="名称" prop="name">
          <el-input
            style="width: 200px"
            maxlength="16"
            v-model.trim="queryParams.name"
            placeholder="请输入优惠券/实物券名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="名称备注" prop="remark">
          <el-input
            style="width: 200px"
            maxlength="30"
            v-model.trim="queryParams.remark"
            placeholder="请输入名称备注"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="queryParams.type" fit-input-width clearable placeholder="全部类型">
            <el-option
              v-for="item in ACTIVITY_TYPE"
              :key="item.type"
              :label="item.title"
              :value="item.type"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        ref="singleTableRef"
        v-loading="loading"
        size="default"
        index
        row-key="id"
        :data="dataList"
        @row-click="handleCurrentChange"
        highlight-current-row
      >
        <el-table-column
          label="优惠券/实物券名称"
          min-width="150px"
          align="center"
          show-overflow-tooltip
          prop="name"
        />
        <el-table-column
          label="名称备注"
          min-width="100px"
          align="center"
          show-overflow-tooltip
          prop="remark"
        />
        <el-table-column label="类型" width="100px" align="center" prop="type">
          <template #default="{ row }">
            <div>
              {{ getType(row.type) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="优惠内容"
          width="150px"
          show-overflow-tooltip
          align="center"
          prop="discounts"
        />
        <el-table-column label="剩余库存" align="center" prop="surplusCount" />
        <el-table-column label="每人限领次数" align="center" prop="receiveCount" />
        <el-table-column label="赠券数" align="center">
          <template #default="{ row }">
            <div
              :class="
                currentRow?.length > 0 && !currentRow[0].grantNum && row.id === currentRow.id
                  ? 'empty'
                  : ''
              "
            >
              <el-input-number
                :controls="false"
                style="width: 90px"
                v-model="row.grantNum"
                :min="1"
                :max="getMax(row)"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-right: 10px">
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
    <template #footer>
      <el-button :loading="submit" type="primary" @click="handleAction(true)"> 保存 </el-button>
      <el-button @click="handleAction(false)">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { listDataApi } from '@/api/system/dict/data'
import { getPrizeListApi } from '@/api/marketing/raffle'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['select'])
const queryRef = ref(null)

const total = ref(0)
const dataList = ref([])
const visible = ref(false)
const submit = ref(false)

const queryParams = reactive({
  name: '',
  type: '', //类型 1满减券2折扣券3单品券4新人券5霸王免单券6实物券 87活动88礼包
  remark: '',
  pageNum: 1,
  pageSize: 10,
  cityName: ''
})
const loading = ref(true)

// =========获取优惠券类型列表
const ACTIVITY_TYPE = ref([])
const getListData = () => {
  listDataApi({ dictType: 'market_activity_type' }).then((res) => {
    ACTIVITY_TYPE.value = res?.rows.map((i) => {
      return {
        title: i.dictLabel,
        dec: i.remark,
        type: i.dictValue - 0
      }
    })
    ACTIVITY_TYPE.value = [
      ...ACTIVITY_TYPE.value,
      { type: 6, title: '实物券' },
      { type: 88, title: '礼包' }
    ]
  })
}
function getType(type) {
  return ACTIVITY_TYPE.value.find((i) => {
    return i.type == type
  })?.title
}

function getMax(row) {
  if (row.type === 88) {
    return 1
  }
  if (row.receiveCount > 0 && row.receiveCount <= row.surplusCount) {
    return row.receiveCount
  } else if (row.surplusCount > 0 && row.receiveCount >= row.surplusCount) {
    return row.surplusCount
  } else {
    return 1
  }
}

/**======================= 查询优惠券列表 */
function getList() {
  loading.value = true
  if (currentRow.value?.length && !currentRow.value[0].grantNum) {
    currentRow.value = []
  }
  getPrizeListApi(queryParams)
    .then((res) => {
      loading.value = false
      dataList.value = res?.data?.rows || []
      dataList.value = dataList.value.map((i, index) => {
        const obj = currentRow.value.find((item) => i.id === item.id)
        if (obj) {
          return {
            ...i,
            grantNum: obj.grantNum,
            ...obj
          }
        } else {
          return {
            ...i,
            grantNum: null
          }
        }
      })
      if (currentRow.value.length > 0) {
        singleTableRef.value?.setCurrentRow(currentRow.value[0])
      }
      total.value = res?.data?.total || 0
    })
    .catch(() => {
      loading.value = false
      dataList.value = []
      total.value = 0
    })
}
// 重置
function resetQuery() {
  const cityName = queryParams.cityName
  queryRef.value.resetFields()
  queryParams.cityName = cityName
  handleQuery()
}
// 查询
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

function onClose(flag) {
  submit.value = false
  queryRef.value.resetFields()
  queryParams.pageNum = 1
  queryParams.pageSize = 10
  if (flag) {
    emit('select', oldRow.value[0])
  }
  visible.value = false
}

//========================= 单选 ==================
const singleTableRef = ref(null)
const currentRow = ref([])
const oldRow = ref([])
// 选择优惠券
function handleCurrentChange(val) {
  currentRow.value = [val]
}

//============================ 提交
function handleAction(confirm) {
  if (confirm) {
    if (!currentRow.value?.length) {
      return ElMessage({
        message: '请选择奖品',
        type: 'error'
      })
    }
    if (currentRow.value?.length > 0 && !currentRow.value[0].grantNum) {
      ElMessage({
        type: 'error',
        message: '请校验数据'
      })
      return
    }
    submit.value = true
    oldRow.value = [...currentRow.value]
    console.log('oldRow.value', oldRow.value)
    onClose(true)
  } else {
    onClose(false)
  }
}

function init(list, cityName) {
  queryParams.cityName = cityName
  visible.value = true
  currentRow.value = list[0]?.name ? [...list] : []
  oldRow.value = list[0]?.name ? [...list] : []
  getList()
  getListData()
}

defineExpose({
  init
})
</script>

<style lang="scss" scoped>
:deep(.pagination-container .el-pagination) {
  right: 20px;
}
.main {
  position: relative;
  transform: translate3d(0, -30px, 0);
}
.type {
  margin-bottom: 20px;
}
:deep(.empty .el-input__wrapper) {
  border: 1px solid red;
}
</style>
